<?php
/**
 * Created by PhpStorm.
 * User: joe
 * Date: 18-9-28
 * Time: 上午10:36
 */

namespace App\Models;

use CodeIgniter\Model;

class TestModel extends Model {
    protected $table      = 'test';  //表名
    protected $primaryKey = 'id';  //索引

    protected $returnType     = 'array';  //返回类型
    protected $useSoftDeletes = false; //使用软删除？表内要有deleted列

    protected $allowedFields = ['name', 'type'];  //允许更新写入的列

    protected $useTimestamps = false;  //使用时间戳

    protected $validationRules    = [];  //验证规则
    protected $validationMessages = [];  //验证返回信息
    protected $skipValidation     = false;  //在所有插入和更新期间，应跳过其他验证

    public function store($user, $room, $page,$test) {
        $dir = WRITEPATH . '/' . $user['id'] . '/' . $room['id'] . '/' . $page['id'] . '/';
        if (!is_dir($dir)) {
            mkdirs($dir);
        }
    }

    public function rank($room,$page,$sort='DESC',$limit=10) {
        return $this->select("user.username as userName,zone.name as zoneName,score,usetime")
            ->where(['room'=>$room,'page'=>$page])
            ->join('users','user.id=test.user','left')
            ->join('zone','zone.id=test.zone','left')
            ->orderBy('score',$sort)
            ->limit($limit)
            ->find();
    }

    public function findUserRank($room,$page,$user,$select="rank") {
        $sql="SELECT {$select} FROM ( SELECT t.*, @rownum := @rownum + 1 AS rank FROM (SELECT @rownum := 0) r, test AS t WHERE room={$room} AND page={$page} ORDER BY t.score DESC ) AS b WHERE b.user={$user}";
        $test=$this->db->query($sql)
                 ->getFirstRow('array');
        return strtolower($select)=="rank"?$test['rank']:$test;
    }

    public function findUserTest($user,$room=null,$page=null) {
        if ($page) $this->where("test.page",$page);
        if ($room) $this->where("test.room",$room);
        $this->select("test.*,room.name as roomName")
             ->where("test.user",$user)
            ->join("room","room.id=test.room")
            ->findAll();
    }

}